﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Data;
using System.Text;
using YiYiTong.Rocket.Helper;
using YiYiTong.Rocket.Entity;
using YiYiTong.Rocket.Model;
using YiYiTong.Rocket.DataAccess;
using YiYiTong.Rocket.EFDBFirst;
using System.Web;

namespace YiYiTong.Rocket.Business
{
    public class SysConfigBiz
    {
        #region 单例模式
        private SysConfigBiz()
        {
        }

        private static SysConfigBiz _instance;
        private static readonly object _syncObject = new object();

        public static SysConfigBiz Instance
        {
            get
            {
                if (_instance == null)
                {
                    lock (_syncObject)
                    {
                        if (_instance == null)
                        {
                            _instance = new SysConfigBiz();
                        }
                    }
                }
                return _instance;
            }
        }
        #endregion 单例模式

        /// <summary>
        /// 获取转发配置
        /// </summary>
        /// <returns></returns>
        public List<SysConfig> GetList(long uid)
        {
            if (uid < 0)
                return null;

            return SysConfigDataAccess.Instance.GetList(uid);
        }

        /// <summary>
        /// 保存转发配置
        /// </summary>
        /// <returns></returns>
        public Tuple<bool, string> Write(long uid, int config_type, string config_code, string config_name, string config_content)
        {
            if (uid < 0)
                return new Tuple<bool, string>(false, "保存失败，用户不存在");

            string stroutput = string.Empty;
            long ret = SysConfigDataAccess.Instance.Write(uid, config_type, config_code, config_name, config_content, out stroutput);
            if (ret > 0)
                return new Tuple<bool, string>(true, "");
            else
                return new Tuple<bool, string>(false, stroutput);
        }

        /// <summary>
        /// 版本检测
        /// </summary>
        /// <param name="system_type">系统类型 1 android 2 ios</param>
        /// <param name="inno_version">内部版本号</param>
        /// <returns></returns>
        public Tuple<bool, GradeInfo> CheckVersion(int system_type, int inno_version)
        {
            //加入缓存，不用每次从数据库读取
            string redisKey = string.Format("checkversion-{0}-{1}", system_type, inno_version);
            //读取缓存数据,去掉缓存
            string redisJson = "";// RedisService.Get<string>(redisKey);
            GradeInfo model = null;
            if (!string.IsNullOrEmpty(redisJson))
            {
                model = JsonHelper.Deserialize<GradeInfo>(redisJson);
            }
            else
            {
                if (model == null)
                {
                    model = SysConfigDataAccess.Instance.GetGradeInfo(system_type);
                    //string newKey = string.Format("checkversion-{0}-{1}", model.SystemVersion, model.InnoVersion);
                    //RedisService.Set(newKey, JsonHelper.Serialize(model));
                }
            }

            if (model != null)
            {
                //内部版本号不相同，表示需要版本更新
                if (inno_version != model.InnoVersion)
                    return new Tuple<bool, GradeInfo>(true, model);
                else
                    return new Tuple<bool, GradeInfo>(false, null);
            }
            else
                return new Tuple<bool, GradeInfo>(false, null);
        }

        /// <summary>
        /// 获取下载地址
        /// </summary>
        /// <returns></returns>
        public Tuple<bool, string> GetDownAddress(int system_type)
        {
            ADZ_MasterEntities dbcontext = new ADZ_MasterEntities();
            var obj = dbcontext.ADZ_APPUpGradeInfo.OrderByDescending(t => t.InnoVersion)
                .FirstOrDefault(t => t.SystemType == system_type && t.IsDel == 0);
            if (obj != null)
            {
                return new Tuple<bool, string>(true, obj.DowloadAddress);
            }
            return new Tuple<bool, string>(false, "");
        }

        /// <summary>
        /// 获取轮播广告配置
        /// </summary>
        /// <param name="num">广告条数</param>
        /// <returns></returns>
        public List<AdConfig> GetAd(int num)
        {
            if (num <= 0)
                num = 100;

            var list = SysConfigDataAccess.Instance.GetAd(num);
            foreach (var item in list)
            {
                //处理图片
                item.img_url = AliyunOssBiz.GetImg(item.img_url);
            }

            return list;
        }

        /// <summary>
        /// 新增广告
        /// </summary>
        /// <returns></returns>
        public Tuple<bool, string> AddAdConfig(ADZ_AdConfig adconfig)
        {
            ADZ_MasterEntities dbcontext = new ADZ_MasterEntities();

            //设置默认值
            adconfig.is_del = 0;
            adconfig.create_time = DateTime.Now;

            HttpFileCollection hfc = HttpContext.Current.Request.Files;
            if (hfc != null && hfc.Count > 0)
            {
                var file = hfc[0];
                var putResult = ImageFileBiz.UpImg(file);
                if (!putResult.Item1)
                    return new Tuple<bool, string>(false, putResult.Item2);
                else
                    adconfig.img_url = putResult.Item3;
            }
            else
                return new Tuple<bool, string>(false, "请上传图片");

            //验证广告名称重复
            var entity = dbcontext.ADZ_AdConfig.FirstOrDefault(t => t.ad_name == adconfig.ad_name && t.is_del == 0);
            if (entity != null)
                return new Tuple<bool, string>(false, "广告已存在");

            dbcontext.ADZ_AdConfig.Add(adconfig);
            if (dbcontext.SaveChanges() > 0)
                return new Tuple<bool, string>(true, "新增成功");
            else
                return new Tuple<bool, string>(false, "新增失败");
        }

        /// <summary>
        /// 修改广告
        /// </summary>
        /// <returns></returns>
        public Tuple<bool, string> EditAdConfig(ADZ_AdConfig adconfig)
        {
            ADZ_MasterEntities dbcontext = new ADZ_MasterEntities();
            if (adconfig.seq_id > 0)
            {
                var entity = dbcontext.ADZ_AdConfig.FirstOrDefault(t => t.seq_id == adconfig.seq_id && t.is_del == 0);
                if (entity == null)
                    return new Tuple<bool, string>(false, "广告不存在");

                if (entity.ad_name != adconfig.ad_name)
                {
                    if (dbcontext.ADZ_AdConfig.FirstOrDefault(t => t.ad_name == adconfig.ad_name && t.is_del == 0) != null)
                        return new Tuple<bool, string>(false, "广告名称已存在");
                }

                entity.ad_name = adconfig.ad_name;
                entity.link_url = adconfig.link_url;
                entity.update_time = DateTime.Now;

                HttpFileCollection hfc = HttpContext.Current.Request.Files;
                if (hfc != null && hfc.Count > 0)
                {
                    var file = hfc[0];
                    var putResult = ImageFileBiz.UpImg(file);
                    if (!putResult.Item1)
                        return new Tuple<bool, string>(false, putResult.Item2);
                    else
                        entity.img_url = putResult.Item3;
                }
                else
                {
                    if (string.IsNullOrWhiteSpace(adconfig.img_url))
                        return new Tuple<bool, string>(false, "请上传图片");
                }

                dbcontext.SaveChanges();
                return new Tuple<bool, string>(true, "编辑成功");
            }
            else
                return new Tuple<bool, string>(false, "品牌不存在");
        }


        /// <summary>
        /// 记录崩溃日志
        /// </summary>
        public Tuple<bool, string> AddLog(string content, string log_source, string device_no, string ip)
        {
            ADZ_MasterEntities dbcontext = new ADZ_MasterEntities();
            ADZ_CollapseLog log = new ADZ_CollapseLog()
            {
                log_content = content,
                log_source = log_source,
                device_no = device_no,
                ip = ip,
                createt_time = DateTime.Now
            };
            dbcontext.ADZ_CollapseLog.Add(log);
            dbcontext.SaveChanges();
            return new Tuple<bool, string>(true, "");
        }

        /// <summary>
        /// 获取银行列表
        /// </summary>
        /// <returns></returns>
        public List<ADZ_Bank> GetBankList()
        {
            ADZ_MasterEntities dbcontext = new ADZ_MasterEntities();
            return dbcontext.ADZ_Bank.ToList();
        }

        /// <summary>
        /// 根据图片保存地址获取真实地址
        /// </summary>
        /// <param name="img_type"> 0 默认</param>
        /// <returns></returns>
        public string GetThingIMG(string old_img_url, int img_type = 0, string imgstyle = "")
        {
            if (string.IsNullOrWhiteSpace(old_img_url))
            {
                if (img_type == 0)
                    return ConfigHelper.AppSetting<string>("good_imgurl");
            }
            if (old_img_url.ToLower().StartsWith("http"))
                return old_img_url;
            else
            {
                return AliyunOssBiz.GetImg(old_img_url, imgstyle);
            }

        }
    }
}
